/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useEffect, useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { RootState, AppDispatch } from "../../store";
import { addMusiclist, updatedMusicId } from "../../store/musicSlice";
import { PlayerContext } from "../../context/PlayerContext";
import musicBg from "../../assets/images/music_bg.png";
import playMode from "../../assets/images/play_mode.png";
import controlLeft from "../../assets/images/control_left.png";
import playBack from "../../assets/images/playBack.svg";
import playIcon from "../../assets/images/play_icon.png";
import controlRight from "../../assets/images/control_right.png";
import musicIcon from "../../assets/images/music_icon.svg";
import heart_icon from "../../assets/images/heart_icon.svg";
import not_heart_icon from "../../assets/images/not_heart_icon.svg";
import "./index.less";

interface MusicFooterProps {
  deviceType?: string;
  listNum?: number;
  musicId?: number;
  oneMusic?: any;
  isPlay?: string;
  onUpdateMusic?: (msg: { musicId: number; getOneMusic: (obj: any) => void }) => void;
}

const MusicFooter: React.FC<MusicFooterProps> = ({
  deviceType = "mobile",
  listNum = 0,
  musicId = 1,
  oneMusic = {},
  isPlay = 'pause',
  onUpdateMusic,
}) => {
  const navigate = useNavigate();
  const dispatch = useDispatch<AppDispatch>();
  const musicList = useSelector((state: RootState) => state.music.musicList);
  const { player } = useContext(PlayerContext);

  // 只用本地 state 管理播放状态
  const [localIsPlay, setLocalIsPlay] = useState<string>(isPlay);

  // 播放或暂停
  const playMusic = (value: string) => {
    setLocalIsPlay(value);
    if (value === 'pause') {
      player.pause();
    } else {
      player.play();
    }
  };

  // 跳转详情
  const goRouter = () => {
    navigate(`/musicListDetail?isPlay=${localIsPlay}&musicId=${musicId}&isPlaying=${localIsPlay}`);
  };

  // 上一曲
  const previousTrack = () => {
    player.pause();
    updateMusic(-1);
  };

  // 下一曲
  const theNextSong = () => {
    player.pause();
    updateMusic(1);
  };

  // 切歌
  const updateMusic = (num: number) => {
    const index = musicList.findIndex((item) => item.id === Number(musicId));
    if (
      (num > 0 && index !== musicList.length - 1) ||
      (num < 0 && index !== 0)
    ) {
      const nextMusic = musicList[index + num];
      if (onUpdateMusic) {
        onUpdateMusic({
          musicId: nextMusic.id,
          getOneMusic,
        });
      }
      dispatch(updatedMusicId(nextMusic.id));
    }
  };

  // 切歌后播放
  const getOneMusic = (obj: any) => {
    player.seekTo(0);
    player.play();
    setLocalIsPlay('play');
  };

  // 首次加载
  useEffect(() => {
    const MusicListCache = sessionStorage.getItem("musicList");
    if (MusicListCache) {
      dispatch(addMusiclist(JSON.parse(MusicListCache)));
    }
    player.seekTo(0);
    player.pause();
    // eslint-disable-next-line
  }, []);

  // 如果 props.isPlay 变化，更新本地播放状态
  useEffect(() => {
    setLocalIsPlay(isPlay);
  }, [isPlay]);

  return (
    <div className="audio_player">
      <div className="bg_info" onClick={goRouter}>
        <img src={musicBg} alt="" />
        <div className="music_name">
          <span>{oneMusic?.name}</span>
          <span>{oneMusic?.musicName}</span>
        </div>
      </div>
      <div className="music_icon">
        {deviceType !== "mobile" && (
          <>
            <img src={playMode} alt="" />
            <img src={controlLeft} alt="" onClick={previousTrack} />
          </>
        )}
        {localIsPlay === 'pause' ? (
          <img src={playBack} alt="" onClick={() => playMusic('play')} />
        ) : (
          <img src={playIcon} alt="" onClick={() => playMusic('pause')} />
        )}
        {deviceType !== "mobile" && (
          <img src={controlRight} alt="" onClick={theNextSong} />
        )}
        <img src={musicIcon} alt="" />
      </div>
      {deviceType !== "mobile" && (
        <div className="music_icon_right">
          <img src={oneMusic?.isCollect ? heart_icon : not_heart_icon} alt="" />
        </div>
      )}
    </div>
  );
};

export default MusicFooter;